// React核心库导入
import React, { createContext, useContext, useReducer, useEffect, ReactNode } from 'react';
// 提示词模板服务导入
import promptTemplateService, {
  PromptTemplateDto,
  PromptTemplateDetailDto,
  CreatePromptTemplateInput,
  UpdatePromptTemplateInput,
  RenderPromptTemplateInput,
  CopyPromptTemplateInput,
  CreatePromptTemplateVersionInput,
  PromptTemplateStatisticsDto,
  GetPromptTemplateListInput,
} from '@services/promptTemplateService';
// 消息提示组件导入
import { message } from 'antd';

// 模板状态接口
interface PromptTemplateState {
  // 模板列表数据
  templates: PromptTemplateDto[];
  // 当前模板详情
  currentTemplate: PromptTemplateDetailDto | null;
  // 加载状态
  loading: boolean;
  // 错误信息
  error: string | null;
  // 总数统计
  totalCount: number;
  // 过滤条件
  filters: GetPromptTemplateListInput;
  // 统计信息
  statistics: PromptTemplateStatisticsDto | null;
  // 分类列表
  categories: string[];
  // 渲染结果
  renderResult: unknown | null;
}

// 模板动作类型
type PromptTemplateAction =
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'SET_ERROR'; payload: string | null }
  | { type: 'SET_TEMPLATES'; payload: { templates: PromptTemplateDto[]; totalCount: number } }
  | { type: 'SET_CURRENT_TEMPLATE'; payload: PromptTemplateDetailDto | null }
  | { type: 'ADD_TEMPLATE'; payload: PromptTemplateDto }
  | { type: 'UPDATE_TEMPLATE'; payload: PromptTemplateDto }
  | { type: 'DELETE_TEMPLATE'; payload: string }
  | { type: 'SET_FILTERS'; payload: Partial<GetPromptTemplateListInput> }
  | { type: 'SET_STATISTICS'; payload: PromptTemplateStatisticsDto }
  | { type: 'SET_CATEGORIES'; payload: string[] }
  | { type: 'SET_RENDER_RESULT'; payload: unknown }
  | { type: 'CLEAR_RENDER_RESULT' };

// 初始状态
const initialState: PromptTemplateState = {
  templates: [],
  currentTemplate: null,
  loading: false,
  error: null,
  totalCount: 0,
  filters: {
    skipCount: 0,
    maxResultCount: 10,
    sorting: 'isSystem desc,version desc,name'
  },
  statistics: null,
  categories: [],
  renderResult: null
};

// Reducer函数
function promptTemplateReducer(state: PromptTemplateState, action: PromptTemplateAction): PromptTemplateState {
  switch (action.type) {
    case 'SET_LOADING':
      return { ...state, loading: action.payload };

    case 'SET_ERROR':
      return { ...state, error: action.payload, loading: false };

    case 'SET_TEMPLATES':
      return {
        ...state,
        templates: action.payload.templates,
        totalCount: action.payload.totalCount,
        loading: false,
        error: null
      };

    case 'SET_CURRENT_TEMPLATE':
      return { ...state, currentTemplate: action.payload, loading: false };

    case 'ADD_TEMPLATE':
      return {
        ...state,
        templates: [action.payload, ...state.templates],
        totalCount: state.totalCount + 1
      };

    case 'UPDATE_TEMPLATE':
      return {
        ...state,
        templates: state.templates.map(template =>
          template.id === action.payload.id ? action.payload : template
        ),
        currentTemplate:
          state.currentTemplate?.id === action.payload.id
            ? { ...state.currentTemplate, ...action.payload }
            : state.currentTemplate
      };

    case 'DELETE_TEMPLATE':
      return {
        ...state,
        templates: state.templates.filter(template => template.id !== action.payload),
        currentTemplate:
          state.currentTemplate?.id === action.payload ? null : state.currentTemplate,
        totalCount: state.totalCount - 1
      };

    case 'SET_FILTERS':
      return {
        ...state,
        filters: { ...state.filters, ...action.payload }
      };

    case 'SET_STATISTICS':
      return { ...state, statistics: action.payload };

    case 'SET_CATEGORIES':
      return { ...state, categories: action.payload };

    case 'SET_RENDER_RESULT':
      return { ...state, renderResult: action.payload };

    case 'CLEAR_RENDER_RESULT':
      return { ...state, renderResult: null };

    default:
      return state;
  }
}

// Context创建
const PromptTemplateContext = createContext<{
  state: PromptTemplateState;
  actions: {
    fetchTemplates: () => void;
    fetchTemplateDetail: (id: string) => void;
    createTemplate: (input: CreatePromptTemplateInput) => Promise<void>;
    updateTemplate: (id: string, input: UpdatePromptTemplateInput) => Promise<void>;
    deleteTemplate: (id: string) => Promise<void>;
    renderTemplate: (id: string, input: RenderPromptTemplateInput) => Promise<void>;
    copyTemplate: (id: string, input: CopyPromptTemplateInput) => Promise<void>;
    createVersion: (id: string, input: CreatePromptTemplateVersionInput) => Promise<void>;
    fetchCategories: () => void;
    fetchStatistics: () => void;
    setFilters: (filters: Partial<GetPromptTemplateListInput>) => void;
    resetFilters: () => void;
    clearRenderResult: () => void;
  };
} | null>(null);

// Provider组件
interface PromptTemplateProviderProps {
  children: ReactNode;
}

export const PromptTemplateProvider: React.FC<PromptTemplateProviderProps> = ({ children }) => {
  const [state, dispatch] = useReducer(promptTemplateReducer, initialState);

  // 获取模板列表
  const fetchTemplates = async () => {
    try {
      dispatch({ type: 'SET_LOADING', payload: true });
      const { items, totalCount } = await promptTemplateService.getPromptTemplateList(state.filters);
      dispatch({ type: 'SET_TEMPLATES', payload: { templates: items, totalCount } });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取模板列表失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
    }
  };

  // 获取模板详情
  const fetchTemplateDetail = async (id: string) => {
    try {
      dispatch({ type: 'SET_LOADING', payload: true });
      const template = await promptTemplateService.getPromptTemplateDetail(id);
      dispatch({ type: 'SET_CURRENT_TEMPLATE', payload: template });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取模板详情失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
    }
  };

  // 创建模板
  const createTemplate = async (input: CreatePromptTemplateInput) => {
    try {
      dispatch({ type: 'SET_LOADING', payload: true });
      const template = await promptTemplateService.createPromptTemplate(input);
      dispatch({ type: 'ADD_TEMPLATE', payload: template });
      message.success('模板创建成功');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '创建模板失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 更新模板
  const updateTemplate = async (id: string, input: UpdatePromptTemplateInput) => {
    try {
      dispatch({ type: 'SET_LOADING', payload: true });
      const template = await promptTemplateService.updatePromptTemplate(id, input);
      dispatch({ type: 'UPDATE_TEMPLATE', payload: template });
      message.success('模板更新成功');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '更新模板失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 删除模板
  const deleteTemplate = async (id: string) => {
    try {
      await promptTemplateService.deletePromptTemplate(id);
      dispatch({ type: 'DELETE_TEMPLATE', payload: id });
      message.success('模板删除成功');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '删除模板失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 渲染模板
  const renderTemplate = async (id: string, input: RenderPromptTemplateInput) => {
    try {
      dispatch({ type: 'SET_LOADING', payload: true });
      const result = await promptTemplateService.renderPromptTemplate(id, input);
      dispatch({ type: 'SET_RENDER_RESULT', payload: result });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '渲染模板失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 复制模板
  const copyTemplate = async (id: string, input: CopyPromptTemplateInput) => {
    try {
      dispatch({ type: 'SET_LOADING', payload: true });
      const template = await promptTemplateService.copyPromptTemplate(id, input);
      dispatch({ type: 'ADD_TEMPLATE', payload: template });
      message.success('模板复制成功');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '复制模板失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 创建版本
  const createVersion = async (id: string, input: CreatePromptTemplateVersionInput) => {
    try {
      dispatch({ type: 'SET_LOADING', payload: true });
      const template = await promptTemplateService.createTemplateVersion(id, input);
      dispatch({ type: 'ADD_TEMPLATE', payload: template });
      message.success('版本创建成功');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '创建版本失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
      throw error;
    }
  };

  // 获取分类列表
  const fetchCategories = async () => {
    try {
      const categories = await promptTemplateService.getTemplateCategories();
      dispatch({ type: 'SET_CATEGORIES', payload: categories });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取分类列表失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
    }
  };

  // 获取统计信息
  const fetchStatistics = async () => {
    try {
      const statistics = await promptTemplateService.getTemplateStatistics();
      dispatch({ type: 'SET_STATISTICS', payload: statistics });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取统计信息失败';
      dispatch({ type: 'SET_ERROR', payload: errorMessage });
      message.error(errorMessage);
    }
  };

  // 设置过滤条件
  const setFilters = (filters: Partial<GetPromptTemplateListInput>) => {
    dispatch({ type: 'SET_FILTERS', payload: filters });
  };

  // 重置过滤条件
  const resetFilters = () => {
    dispatch({
      type: 'SET_FILTERS',
      payload: {
        skipCount: 0,
        maxResultCount: 10,
        sorting: 'isSystem desc,version desc,name'
      }
    });
  };

  // 清除渲染结果
  const clearRenderResult = () => {
    dispatch({ type: 'CLEAR_RENDER_RESULT' });
  };

  // 监听过滤条件变化，自动刷新数据
  useEffect(() => {
    fetchTemplates();
  }, [state.filters]);

  // 初始化数据
  useEffect(() => {
    fetchCategories();
    fetchStatistics();
  }, []);

  const actions = {
    fetchTemplates,
    fetchTemplateDetail,
    createTemplate,
    updateTemplate,
    deleteTemplate,
    renderTemplate,
    copyTemplate,
    createVersion,
    fetchCategories,
    fetchStatistics,
    setFilters,
    resetFilters,
    clearRenderResult
  };

  return (
    <PromptTemplateContext.Provider value={{ state, actions }}>
      {children}
    </PromptTemplateContext.Provider>
  );
};

// Hook函数
export const usePromptTemplate = () => {
  const context = useContext(PromptTemplateContext);
  if (!context) {
    throw new Error('usePromptTemplate must be used within a PromptTemplateProvider');
  }
  return context;
};

// 选择器Hook
export const useTemplates = () => {
  const { state } = usePromptTemplate();
  return state.templates;
};

export const useTemplateLoading = () => {
  const { state } = usePromptTemplate();
  return state.loading;
};

export const useTemplateError = () => {
  const { state } = usePromptTemplate();
  return state.error;
};

export const useTemplateFilters = () => {
  const { state, actions } = usePromptTemplate();
  return {
    filters: state.filters,
    setFilters: actions.setFilters,
    resetFilters: actions.resetFilters
  };
};

export const useCurrentTemplate = () => {
  const { state } = usePromptTemplate();
  return state.currentTemplate;
};

export const useTemplateStatistics = () => {
  const { state, actions } = usePromptTemplate();
  return {
    statistics: state.statistics,
    fetchStatistics: actions.fetchStatistics
  };
};

export const useTemplateCategories = () => {
  const { state } = usePromptTemplate();
  return state.categories;
};

export const useTemplateRender = () => {
  const { state, actions } = usePromptTemplate();
  return {
    renderResult: state.renderResult,
    renderTemplate: actions.renderTemplate,
    clearRenderResult: actions.clearRenderResult
  };
};